package com.example.demo.controller;

import com.example.demo.config.AESUtil;
import com.example.demo.config.Result;
import com.example.demo.entity.user.InsertUser;
import com.example.demo.entity.user.User;
import com.example.demo.service.LogService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import javax.crypto.SecretKey;
import java.util.List;

@Tag(name = "Conf API", description = "conf配置")
@RestController
@RequestMapping("/conf")
public class ConfController {
    @Value("${aes.secretKey}")
    byte[] aesSecretKey;
    @Autowired
    private LogService logService;


    @Operation(summary = "生成秘钥", tags = "Conf API")
    @RequestMapping(value = "/getAesKey", produces = "application/json;charset=utf-8", method = RequestMethod.GET)
    public Result getAesKey() throws Exception {
        if (aesSecretKey.length == 0) {
            SecretKey key = logService.getAesKey();
            aesSecretKey = key.getEncoded();
            return Result.success(aesSecretKey);
        } else {
            return Result.success(aesSecretKey);
        }
    }

    @Operation(summary = "AES加密", tags = "Conf API")
    @RequestMapping(value = "/aesEncrypt", produces = "application/json;charset=utf-8", method = RequestMethod.GET)
    public Result aesEncrypt(@RequestParam String aesCode) throws Exception {
        try {
            String encryption = AESUtil.encrypt(aesCode);
            return Result.success(encryption);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("加密失败");
        }
    }

    @Operation(summary = "AES解密", tags = "Conf API")
    @RequestMapping(value = "/aesDecrypt", produces = "application/json;charset=utf-8", method = RequestMethod.GET)
    public Result aesDecrypt(@RequestParam String aesCode) throws Exception {
        try {
            String encryption = AESUtil.decrypt(aesCode);
            return Result.success(encryption);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("解密失败");
        }
    }

    @Operation(summary = "MD5加密", tags = "Conf API")
    @RequestMapping(value = "/mdEncryption", produces = "application/json;charset=utf-8", method = RequestMethod.GET)
    public Result mdEncryption(@RequestParam String mdCode) {
        try {
            String encryption = AESUtil.mdEncryption(mdCode);
            return Result.success(encryption);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("md5加密失败");
        }

    }
}
